from flask import Flask, render_template, request, redirect, url_for, session, jsonify, flash
from datetime import datetime
import mysql.connector

app = Flask(__name__)
app.secret_key = 'your_secret_key'
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = {'docx'}

# 数据库配置
DB_CONFIG = {
    'host': '152.136.49.229',
    'user': 'yuyu',
    'password': '123456',
    'database': 'yuyude',
    'charset': 'utf8mb4'
}

# 数据库连接函数
def get_db_connection():
    try:
        conn = mysql.connector.connect(**DB_CONFIG)
        return conn
    except mysql.connector.Error as err:
        print(f"数据库连接失败: {err}")
        return None

# 登录页面
@app.route('/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        user_type = request.form['user_type']
        username = request.form['username']
        password = request.form['password']

        conn = get_db_connection()
        if conn:
            cursor = conn.cursor(dictionary=True)
            query = "SELECT * FROM users WHERE username=%s AND password=%s AND role=%s"
            cursor.execute(query, (username, password, user_type))
            user = cursor.fetchone()
            cursor.close()
            conn.close()

            if user:
                session['username'] = username
                session['user_type'] = user_type
                if user_type == 'student':
                    return redirect(url_for('student_dashboard', username=username))
                elif user_type == 'teacher':
                    return redirect(url_for('teacher_dashboard', username=username))
                elif user_type == 'parent':
                    return redirect(url_for('parent_dashboard', username=username))
            else:
                flash('登录失败，用户名或密码错误！', 'danger')
                return redirect(url_for('login'))
        else:
            flash('数据库连接失败，请稍后重试。', 'danger')
            return redirect(url_for('login'))

    return render_template('login.html')

# 注册页面
@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        user_type = request.form['user_type']
        username = request.form['username']
        user_id = request.form['id']
        password = request.form['password']

        conn = get_db_connection()
        if conn:
            cursor = conn.cursor(dictionary=True)
            cursor.execute("SELECT * FROM users WHERE username=%s", (username,))
            existing_user = cursor.fetchone()

            if existing_user:
                flash('用户名已存在，请选择其他用户名。', 'danger')
                cursor.close()
                conn.close()
                return redirect(url_for('register'))

            try:
                cursor.execute(
                    "INSERT INTO users (username, password, id, role) VALUES (%s, %s, %s, %s)",
                    (username, password, user_id, user_type)
                )
                conn.commit()
                flash('注册成功！', 'success')
            except mysql.connector.Error as err:
                flash(f'注册失败: {err}', 'danger')
            finally:
                cursor.close()
                conn.close()
                return redirect(url_for('register_success'))

        else:
            flash('数据库连接失败，请稍后重试。', 'danger')
            return redirect(url_for('register'))

    return render_template('register.html')

@app.route('/register_success')
def register_success():
    return render_template('register_success.html')

# 忘记密码页面
@app.route('/forgot_password', methods=['GET', 'POST'])
def forgot_password():
    if request.method == 'POST':
        user_type = request.form['user_type']
        username = request.form['username']
        new_password = request.form['new_password']

        conn = get_db_connection()
        if conn:
            cursor = conn.cursor(dictionary=True)
            cursor.execute("SELECT * FROM users WHERE username=%s AND role=%s", (username, user_type))
            user = cursor.fetchone()

            if user:
                try:
                    cursor.execute(
                        "UPDATE users SET password=%s WHERE username=%s AND role=%s",
                        (new_password, username, user_type)
                    )
                    conn.commit()
                    flash('密码重置成功！', 'success')
                except mysql.connector.Error as err:
                    flash(f'密码重置失败: {err}', 'danger')
            else:
                flash('用户名不存在。', 'danger')

            cursor.close()
            conn.close()
            return redirect(url_for('password_reset_success'))
        else:
            flash('数据库连接失败，请稍后重试。', 'danger')
            return redirect(url_for('forgot_password'))

    return render_template('forgot_password.html')

@app.route('/password_reset_success')
def password_reset_success():
    return render_template('password_reset_success.html')

# 学生主页
@app.route('/student_dashboard/<username>', methods=['GET', 'POST'])
def student_dashboard(username):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    conn = get_db_connection()
    if not conn:
        flash('数据库连接失败，请稍后重试。', 'danger')
        return redirect(url_for('login'))

    cursor = conn.cursor(dictionary=True)

    if request.method == 'POST':
        class_name = request.form.get('class_name')
        if not class_name:
            flash('班级名称不能为空。', 'danger')
        else:
            try:
                # 更新用户表中的班级信息
                cursor.execute(
                    "UPDATE users SET class_name=%s WHERE username=%s AND role='student'",
                    (class_name, username)
                )
                conn.commit()
                flash(f'成功加入班级 {class_name}！', 'success')

                # 跳转到准备考试页面
                return redirect(url_for('exam_ready', class_name=class_name, username=username))

            except mysql.connector.Error as err:
                flash(f'加入班级失败: {err}', 'danger')

    # 获取学生当前的班级信息
    cursor.execute(
        "SELECT class_name FROM users WHERE username=%s AND role='student'",
        (username,)
    )
    student_class = cursor.fetchone()
    student_class_name = student_class['class_name'] if student_class else None

    cursor.close()
    conn.close()

    return render_template('student_dashboard.html', username=username, class_name=student_class_name)

# 准备考试页面
@app.route('/exam_ready/<class_name>/<username>', methods=['GET', 'POST'])
def exam_ready(class_name, username):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    conn = get_db_connection()
    if not conn:
        flash('数据库连接失败，请稍后重试。', 'danger')
        return redirect(url_for('login'))

    cursor = conn.cursor(dictionary=True)

    try:
        cursor.execute("SELECT name FROM exams WHERE class_name=%s AND published=TRUE", (class_name,))
        exams = cursor.fetchall()
    except mysql.connector.Error as err:
        flash(f"查询考试列表时出错: {err}", 'danger')
        exams = []

    cursor.close()
    conn.close()

    if request.method == 'POST':
        exam_name = request.form.get('exam_name')
        if exam_name:
            # 跳转到考试页面
            return redirect(url_for('exam_page', class_name=class_name, exam_name=exam_name))

    return render_template('exam_ready.html', class_name=class_name, username=username, exams=exams)


# 考试页面
@app.route('/exam/<class_name>/<exam_name>', methods=['GET', 'POST'])
def exam_page(class_name, exam_name):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    conn = get_db_connection()
    if not conn:
        flash('数据库连接失败，请稍后重试。', 'danger')
        return redirect(url_for('login'))

    cursor = conn.cursor(dictionary=True)
    cursor.execute("SELECT id FROM exams WHERE class_name=%s AND name=%s", (class_name, exam_name))
    exam = cursor.fetchone()
    exam_id = exam['id']

    cursor.execute("SELECT * FROM questions WHERE exam_id=%s", (exam_id,))
    questions = cursor.fetchall()

    # 检查是否已经设置了考试开始时间
    if 'exam_start_time' not in session:
        session['exam_start_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')

    remaining_seconds = 3600  # 假设剩余考试时间为 1 小时
    if request.method == 'POST':
        # 处理考试提交逻辑
        return redirect(url_for('submit_exam', class_name=class_name, exam_name=exam_name))

    return render_template(
        'exam.html',
        remaining_time=remaining_seconds,
        class_name=class_name,
        exam_name=exam_name,
        questions=questions
    )

# 提交考试页面
@app.route('/submit_exam/<class_name>/<exam_name>', methods=['POST'])
def submit_exam(class_name, exam_name):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    try:
        exam_start_time_str = session.get('exam_start_time')
        if not exam_start_time_str:
            raise ValueError("考试开始时间未找到")

        exam_start_time = datetime.strptime(exam_start_time_str, '%Y-%m-%d %H:%M:%S.%f')
        elapsed_time = datetime.now() - exam_start_time
        elapsed_seconds = int(elapsed_time.total_seconds())

        session.pop('exam', None)
        session.pop('exam_start_time', None)

        return render_template('exam_finished.html', class_name=class_name, exam_name=exam_name,
                               elapsed_seconds=elapsed_seconds, username=session['username'])
    except Exception as e:
        return render_template('exam_finished.html', class_name=class_name, exam_name=exam_name, error=str(e),
                               username=session['username'])

# 考试完成页面
@app.route('/exam_finished/<class_name>/<exam_name>', methods=['GET'])
def exam_finished(class_name, exam_name):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    return render_template(
        'exam_finished.html',
        class_name=class_name,
        exam_name=exam_name,
        username=session['username']
    )


# 老师主页
@app.route('/teacher_dashboard/<username>', methods=['GET', 'POST'])
def teacher_dashboard(username):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    if request.method == 'POST':
        if 'add_exam' in request.form:
            return redirect(url_for('create_exam', username=username))
        elif 'manage_class' in request.form:
            return redirect(url_for('manage_class', username=username))

    return render_template('teacher_dashboard.html', username=username)


# 创建考试页面
@app.route('/create_exam/<username>', methods=['GET', 'POST'])
def create_exam(username):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    if request.method == 'POST':
        exam_title = request.form.get('exam_title')
        exam_description = request.form.get('exam_description')
        class_name = request.form.get('class_name')

        conn = get_db_connection()
        if conn:
            cursor = conn.cursor()
            try:
                cursor.execute(
                    "INSERT INTO exams (name, description, class_name, published) VALUES (%s, %s, %s, %s)",
                    (exam_title, exam_description, class_name, False)  # 初始未发布
                )
                exam_id = cursor.lastrowid  # 获取新创建的考试ID
                conn.commit()
                flash('考试创建成功！现在可以发布考试。', 'success')
                return redirect(url_for('publish_exam', exam_id=exam_id))  # 跳转到发布考试
            except mysql.connector.Error as err:
                flash(f'考试创建失败: {err}', 'danger')
            finally:
                cursor.close()
                conn.close()
        else:
            flash('数据库连接失败，请稍后重试。', 'danger')

    return render_template('create_exam.html', username=username)

# 发布考试
@app.route('/publish_exam/<int:exam_id>', methods=['POST'])
def publish_exam(exam_id):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    conn = get_db_connection()
    if not conn:
        flash('数据库连接失败，请稍后重试。', 'danger')
        return redirect(url_for('teacher_dashboard', username=session['username']))

    cursor = conn.cursor()
    try:
        cursor.execute(
            "UPDATE exams SET published=TRUE WHERE id=%s",
            (exam_id,)
        )
        conn.commit()
        flash('考试已发布！', 'success')
    except mysql.connector.Error as err:
        flash(f'发布考试失败: {err}', 'danger')
    finally:
        cursor.close()
        conn.close()

    return redirect(url_for('teacher_dashboard', username=session['username']))

# 管理班级页面
@app.route('/manage_class/<username>', methods=['GET', 'POST'])
def manage_class(username):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    if request.method == 'POST':
        class_name = request.form.get('class_name')
        if class_name:
            return redirect(url_for('class_management', class_name=class_name))
        else:
            flash('请输入班级名称', 'danger')

    return render_template('manage_class.html', username=username)


# 班级管理详情页面
@app.route('/class_management/<class_name>', methods=['GET', 'POST'])
def class_management(class_name):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    conn = get_db_connection()
    if not conn:
        flash('数据库连接失败，请稍后重试。', 'danger')
        return redirect(url_for('teacher_dashboard', username=session.get('username')))

    cursor = conn.cursor(dictionary=True)

    # 查询 users 表中所有属于该班级的学生
    cursor.execute(
        """
        SELECT username, id 
        FROM users 
        WHERE class_name = %s AND role = 'student'
        """,
        (class_name,)
    )
    students = cursor.fetchall()

    cursor.close()
    conn.close()

    return render_template('class_management.html', class_name=class_name, students=students)


# 删除学生的路由
@app.route('/delete_student/<int:student_id>/<class_name>', methods=['POST'])
def delete_student(student_id, class_name):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    print(f"Deleting student with ID: {student_id} from class: {class_name}")  # 调试信息

    conn = get_db_connection()
    if not conn:
        flash('数据库连接失败，请稍后重试。', 'danger')
        return redirect(url_for('class_management', class_name=class_name))

    cursor = conn.cursor()
    try:
        # 删除与学生相关联的记录
        cursor.execute("DELETE FROM student_classes WHERE student_id = %s", (student_id,))
        conn.commit()

        # 删除学生
        cursor.execute("DELETE FROM users WHERE id = %s AND role = 'student'", (student_id,))
        conn.commit()
        flash('学生已成功删除！', 'success')
    except mysql.connector.Error as err:
        flash(f'删除学生失败: {err}', 'danger')
    finally:
        cursor.close()
        conn.close()

    return redirect(url_for('class_management', class_name=class_name))


# 家长主页
@app.route('/parent_dashboard/<username>')
def parent_dashboard(username):
    if 'user_type' not in session or session['user_type'] != 'parent':
        return redirect(url_for('login'))

    return render_template('parent_dashboard.html', username=username)


# 记录作弊行为
@app.route('/record_cheating', methods=['POST'])
def record_cheating():
    if 'username' in session:
        username = session['username']
        conn = get_db_connection()
        if conn:
            cursor = conn.cursor(dictionary=True)
            cursor.execute(
                "SELECT cheating_count FROM users WHERE username=%s",
                (username,)
            )
            result = cursor.fetchone()
            cheating_count = result.get('cheating_count', 0) if result else 0

            cheating_count += 1

            cursor.execute(
                "UPDATE users SET cheating_count=%s WHERE username=%s",
                (cheating_count, username)
            )
            conn.commit()
            cursor.close()
            conn.close()

            max_cheat_attempts = 2
            if cheating_count > max_cheat_attempts:
                return jsonify({'terminate': True})
            return jsonify({'terminate': False})
        else:
            return jsonify({'error': '数据库连接失败'}), 500
    return jsonify({'error': '用户未登录'}), 401

# 终止考试
@app.route('/terminate_exam')
def terminate_exam():
    session.pop('exam', None)
    flash("由于检测到多次作弊行为，您的考试已被终止。", 'danger')
    return redirect(url_for('login'))

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000, debug=True)
